<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="固件名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入固件名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="升级包类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择升级包类型" clearable>
          <el-option
            v-for="dict in dict.type.firmware_upgrade_filet_ype"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['firmware:firmwareUpgrade:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['firmware:firmwareUpgrade:edit']"
        >修改</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['firmware:firmwareUpgrade:remove']"
        >删除</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['firmware:firmwareUpgrade:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="firmwareUpgradeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="住键" align="center" prop="id" /> -->
      <el-table-column label="固件名称" align="center" prop="name" />
      <el-table-column label="固件版本号" align="center" prop="version" />
      <!-- <el-table-column label="升级包类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.firmware_upgrade_filet_ype" :value="scope.row.type"/>
        </template>
      </el-table-column> -->
      <el-table-column label="文件大小" align="center" prop="fileSizeLabel" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleUpdate(scope.row)"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-thumb"
            @click="upgradeLog(scope.row)"
          >升级日志</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-thumb"
            @click="selectDevice(scope.row)"
            v-hasPermi="['firmware:firmwareUpgrade:edit']"
          >升级</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['firmware:firmwareUpgrade:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改固件升级管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="填写固件名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入固件名称" :disabled="form.id"/>
        </el-form-item>
        <el-form-item label="填写固件版本号" prop="version">
          <el-input v-model="form.version" placeholder="固件版本号格式为:0.0.0" :disabled="form.id"/>
        </el-form-item>
        <el-form-item label="升级文件" prop="fileName" v-if="form.id">
          {{form.fileName}}
        </el-form-item>
        <el-form-item label="上传升级包" prop="fileId" v-if="form.id==null">
          <el-upload
            v-model="form.fileId"
            style="width: 70%"
            class="upload-demo"
            :headers="{Authorization:token}"
            :action="uploadURL"
            :on-remove="handleRemove"
            :on-success="uploadSuccess"
            :multiple="false"
            accept="akp,zip"
            :limit="1"
            :file-list="fileList">
            <el-button icon="el-icon-upload2" >上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="form.id">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择升级设备列表 -->
    <el-dialog title="选择升级设备" :visible.sync="deviceListOpen" width="800px" append-to-body>
      <el-form :inline="true">
        <el-form-item  style="width: 250px;">
          <treeselect v-model="deviceParams.ancestors" :options="deptOptions" @select="monitor" :show-count="true" placeholder="请选择所属分组" />
        </el-form-item>
        <el-form-item >
          <el-input
            v-model="deviceParams.name"
            placeholder="设备名称"
            clearable
            @keyup.enter.native="getDeviceList"
          />
        </el-form-item>
        <el-form-item >
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="getDeviceList"
          >搜素</el-button>
        </el-form-item>
      </el-form>
      
      <el-table v-loading="loading" :data="deviceList" @selection-change="handleUpgradeChange">
        <el-table-column type="selection" width="55" align="center" :selectable="canSelect" />
        <el-table-column label="设备名称" align="center" prop="name" />
        <el-table-column label="设备编号" align="center" prop="code" />
        <el-table-column label="软件版本号" align="center" prop="version" />
        <el-table-column label="在线状态" align="center" prop="inline" >
          <template slot-scope="scope">
            <dict-tag :options="dict.type.online_status" :value="scope.row.inline"/>
          </template>
        </el-table-column>
      </el-table>
    
      <pagination
        v-show="deviceTotal>0"
        :total="deviceTotal"
        :page.sync="deviceParams.pageNum"
        :limit.sync="deviceParams.pageSize"
        @pagination="getDeviceList"
      />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpgrade" :disabled="deviceIds.length === 0">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改固件升级管理对话框 -->
    <el-dialog title="升级进度" :visible.sync="progressPopup" width="1000px" append-to-body>
      <el-table  :data="progressData" >
        <el-table-column label="设备名称" align="center" prop="deviceName" />
        <el-table-column label="设备编号" align="center" prop="code" />
        <el-table-column label="设备版本" align="center" prop="prevVersion" />
        <el-table-column label="升级版本" align="center" prop="upgradeVersion" />
        <el-table-column label="升级状态" align="center" prop="status" >
          <template slot-scope="scope">
            <dict-tag :options="dict.type.upgrade_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="升级进度" align="center" prop="fileSizeLabel" width="130" >
          <template slot-scope="scope"> 
            <el-progress :percentage="getPercentage(scope.row.process)" :text-inside="false" style="width: 120px;" ></el-progress>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="progressTotal>0"
        :total="progressTotal"
        :page.sync="progressParams.pageNum"
        :limit.sync="progressParams.pageSize"
        @pagination="checkProgressData"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeProgressPopup">关  闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFirmwareUpgrade, getFirmwareUpgrade, delFirmwareUpgrade, addFirmwareUpgrade, updateFirmwareUpgrade ,upgrade,firmwareUpgradelog} from "@/api/firmware/firmwareUpgrade";
import { listDevice} from "@/api/device/device";
import { getToken } from '@/utils/auth'
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "FirmwareUpgrade",
  dicts: ['firmware_upgrade_filet_ype','online_status','upgrade_status'],
  components: { Treeselect},
  data() {
    return {
      uploadURL:process.env.VUE_APP_BASE_API+'/system/files?module=firmware_upgrade',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      fileList:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 固件升级管理表格数据
      firmwareUpgradeList: [],
      deviceList:[],
      deviceIds:[],
      deptOptions:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      deviceListOpen:false,
      token:'',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        type: null
      },
      deviceParams:{
        pageNum: 1,
        pageSize: 10,
        ancestors:null,
        name:null
      },
      deviceTotal:0,
      upgradeForm:{
        id:'',
        deviceIds:[]
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "固件名称不能为空", trigger: "blur" }
        ],
        version: [
          { required: true, message: "固件版本号不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "升级包类型不能为空", trigger: "change" }
        ],
        fileId: [
          { required: true, message: "文件Id不能为空", trigger: "blur" }
        ]
      },
      progressParams:{
        pageNum: 1,
        pageSize: 10,
        firmwareUpgradeTaskId:null
      },
      progressPopup:false,
      progressData:[],
      progressTotal:0,
      progressTimer:null
    };
  },
  computed:{
    getPercentage(){
      return (string)=>{
        let perc = 0;
        if(string){
          let arr = string.split('/');
          perc = parseFloat(((parseInt(arr[0])/parseInt(arr[1]))*100).toFixed(2))
        }
        return perc
      }
    }
  },
  created() {
    this.getList();
    this.token = 'Bearer ' + getToken();
    this.getTreeselect()
  },
  
  methods: {
    /** 查询固件升级管理列表 */
    getList() {
      this.loading = true;
      listFirmwareUpgrade(this.queryParams).then(response => {
        this.firmwareUpgradeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    monitor(data){
      console.log(data)
      this.deviceParams.ancestors = data.ancestors;
      this.getDeviceList()
    },
    selectDevice(row){
        this.upgradeForm.id = row.id
        this.upgradeForm.version = row.version;
        this.deviceListOpen = true;
        this.getDeviceList()
    },
    getDeviceList(){
      listDevice(this.deviceParams).then(res => {
        this.deviceTotal = res.total;
        this.deviceList = res.rows;
      })
    },
    upgradeLog(row){
      this.$router.push({path:'firmwareLog',query:{id:row.id}})
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.deviceListOpen = false ;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        version: null,
        type: null,
        fileId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleUpgradeChange(selection){
      this.deviceIds = selection.map(item => item.id)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.fileList = []
      this.reset();
      this.open = true;
      this.title = "添加固件升级管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getFirmwareUpgrade(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改固件升级管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateFirmwareUpgrade(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFirmwareUpgrade(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除固件升级管理编号为"' + ids + '"的数据项？').then(function() {
        return delFirmwareUpgrade(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    uploadSuccess(res){
      this.$set(this.form,'fileId',res.data.id)
      this.$refs["form"].clearValidate('fileId')
    },
    handleRemove(){
      this.form.fileId = '';
    },
    submitUpgrade(){
      this.upgradeForm.deviceIds = this.deviceIds
      upgrade(this.upgradeForm).then(res =>{
        this.$modal.msgSuccess("操作成功!");
        this.deviceListOpen = false;
        this.checkProgressData(res.data.taskId)
      })
    },
    checkProgressData(id){
      if(id){
        this.progressParams.firmwareUpgradeTaskId = id;
      }
      firmwareUpgradelog(this.progressParams).then(res=>{
        this.progressData = res.rows;
        this.progressPopup = true;
        this.progressTotal = res.total;
        this.progressTimer = setTimeout(()=>{
          this.checkProgressData()
        },3000)
      })
    },
    closeProgressPopup(){
      this.progressPopup = false;
    },
    canSelect(row,index){
      if(row.inline===1){
        return true
      }else {
        return false
      }
    }
  },
  watch:{
    progressPopup(v){
      if(!v){
        this.progressTimer&&clearTimeout(this.progressTimer)
      }
    }
  }
};
</script>

<style lang="scss" scoped >
  ::v-deep .vue-treeselect__control{
    height: 32px !important;
  }
</style>
